/**
 * Created by LMN on 2016/7/26.
 * Cache for user auth.
 */
var db = require('./seq.js');
var config = require('../config');
var auths = {};
/**
 * Cache user(or all users) authority.
 * @param username , the user need to cache.
 */
var getAuth = function(username){
    //If username is null, then cache all users' authorities.
    if(username){
        db.user.find({
            where: {username: username},
            attributes: ['username','auth']
        }).then(function (user) {
            auths[user.username] = user.auth;
        })
    }else{
        db.user.findAll({
            attributes: ['username','auth']
        }).then(function(users){
            users.forEach(function (user) {
                auths[user.username] = user.auth;
            });
        });
    }
};
//Cache all users when service starts running.
setTimeout(getAuth, 1000);
/**
 * Delete the cache of an user's authority.
 * @param username , the user need to delete.
 */
var deleteAuth = function(username){
    delete auths[username];
};

module.exports = {
    obj : auths,
    getAuth: getAuth,
    deleteAuth: deleteAuth,
    /**
     * Check if this session is login.
     * @param req
     * @param res
     * @param next
     */
    check: function(req, res, next){
        if(!req.session.username){
            res.redirect('/login.html');
        }else{
            next();
        }
    }
};